package hate.controller;

import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import hate.json.CheckLogin;
import hate.json.GetToken;
import hate.json.ResUtil;
import hate.model.User;
import hate.util.StringUtils;
import io.ebean.EbeanServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录管理
 */
@CrossOrigin(origins = "http://localhost", maxAge = 3600)
@Controller
@RestController
@EnableAutoConfiguration
@RequestMapping("/login")
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ResUtil res=new ResUtil();//返回类

    @Autowired
    private EbeanServer ebeanServer;

    @GetMapping(value = "/getToken")
    @ResponseBody
    public GetToken getToken(){
        GetToken res=new GetToken();
        logger.info("67000");
        res.setId("1");
        res.setToken(StringUtils.getGUID());
        return res;
    }

    //根据用户名密码来查询登录成功与否
    @ResponseBody
    @PostMapping(value = "/loginCheck")
    public ResUtil login(HttpServletRequest request, HttpServletResponse resp) {

        HttpSession hs = request.getSession();
        String account =request.getParameter("account");
        String password =request.getParameter("password");
        System.out.println(" account:"+account);

        User user=ebeanServer.find(User.class).where().eq("account",account).eq("password",password).findOne();
        CheckLogin checkLogin=new CheckLogin();
        if(user!=null){
            res.setCode("success");
            checkLogin.setUserId(String.valueOf(user.getId()));
            checkLogin.setToken(StringUtils.getGUID());
            checkLogin.setRes("ok");

            String token=StringUtils.getGUID();
            StringUtils.map.put(account,token);
            Cookie tokenCookie = new Cookie(account, token);
            tokenCookie.setPath("/");
            tokenCookie.setMaxAge(60*60*24*30);
            System.out.println(" account:"+account);
            System.out.println(" token:"+token);
            hs.setAttribute("account", account);
            hs.setAttribute("token", token);
            resp.addCookie(tokenCookie);

        }else{
            res.setCode("fail");
            checkLogin.setRes("ng");
        }
        res.setData(checkLogin);
        return res;
    }

}